<template>
  <div class="home">
    <div class="btns">
      <el-button>本站开放API</el-button>
      <el-button>待办清单</el-button>
      <el-button>分享文章</el-button>
      <el-button>分享项目</el-button>
      <el-button>常见APP下载</el-button>
      <el-button>问答征集</el-button>
    </div>
    <Card :title="cardData[0].title">
      <template #content>
        <p>消息中心: {{'需登录'}}</p>
        <p>本站积分: {{'需登录'}}</p>
        <p><span>积分规则</span> <span>积分排行榜</span></p>
      </template>
    </Card>
    <Card :title="cardData[1].title">
      <template #content>
        <dl v-for="(item, idx) in friendData" :key="idx">
          <dt>{{item.title}}</dt>
          <dd v-for="val in item.children" :key="val.id">{{val.name}}</dd>
        </dl>
      </template>
    </Card>
    <Card title="推荐">
      <span>文字</span>
      <span>文字</span>
      <span>文字</span>
      <span>文字</span>
      <span>文字</span>
      <span>文字</span>
      <span>文字</span>
    </Card>
  </div>
</template>

<script>
import Card from '@/components/Card.vue'
import { getFriend } from '@/api'

export default {
  name: 'HomeAside',
  data() {
    return {
      cardData:[{
        title:"个人信息&福利"
      },{
        title:"常用网站"
      }],
      friendData: []
    }
  },
  components: {
    Card
  },
  created (){
    getFriend().then(res=>{
      // 保存请求成功后的数据
      const titleArr = res.data.data;

      // [{category:"源码",name:"二级标题1"},{category:"源码",name:"二级标题2"},..]
      // ↑↑↑处理成↓↓↓
      // [{title:"源码",children:[{title:"二级标题1"},{title:"二级标题2"},...]},...]

      // 对一级菜单去重处理
      this.friendData = this.noRepeat(titleArr);
      
      // 将一级菜单对应的二次菜单添加到一级菜单的children属性内
      this.friendData.forEach(val=>{
        titleArr.forEach(item=>{
          if(val.title === item.category){
            val.children.push({
              id: item.id,
              link: item.link,
              name: item.name
            })
          }
        })
      })
    })
  },
  methods: {
    indexOf(arr, title){
      // 根据某个数据，查询数组中的对象内是否存在
      for(let i=0;i<arr.length;i++){
        if(arr[i].title === title){
          return true;
        }
      }
      return false;
    },
    noRepeat(arr){
      // 对多个对象的数组，进行重复属性的去重
      const ls = [];
      for(let i=0;i<arr.length;i++){
        if(!this.indexOf(ls, arr[i].category)){
          ls.push({
            title: arr[i].category,
            children: []
          })
        }
      }
      return ls;
    }
  }
}
</script>
